<?php

namespace co2_OS;

use co2\dev\v0_0_0 as api;

function uninstall_app($app,$version=null,$channel='stable',$clean=false)

{
	log::register("UNINSTALL_APP: Received uninstall signal for app $app in channel $channel");
	
	if(is_null($version))
	log::register("UNINSTALL_APP: No version specified. Will uninstall any version found");
	
	$aptitude=aptitude::get(aptitude::TYPE_APP,$app,$version,$channel);
	
	if(!count($aptitude))
	
	{
	  log::register("UNINSTALL_APP: App '$app@$version#$channel' is not installed.");
	  
	  throw new api\Exception('App not installed',null,ES_PACKAGE_NOT_FOUND);
	}
	
	foreach($aptitude as $pkg)
	
	{
	  $junkies=dependency::getjunkies((int)$pkg->id);
	  
	  if(count($junkies))
	  
	  {
	    if(!$clean)
	    
	    {
	      log::register("UNINSTALL_APP: App cannot be installed as it will created dependency issues with ".count($junkies)." package(s)");
	      
	      $list='';
	      
	      foreach($junkies as $j)
	      
	      {
	        $pkg=aptitude::fetch($j->junkie);
    
          $type=aptitude::type($pkg->type);

	        $list.="  $j->junkie) $type $pkg->pkg version $pkg->version channel $pkg->channel".PHP_EOL;
	      }
	      
	      throw new api\Exception('Other packages depend on this one. Either manually remove junkies or specify the "--junkies y" parameter. The junkies are the following: '.PHP_EOL.PHP_EOL.$list); 
	    }
	    
	    foreach($junkies as $j)
	    
	    {
	      $junky=aptitude::fetch($j->junkie);

	      $function="co2_OS\\uninstall_".aptitude::type($junky->type);
	      
	      $function($junky->pkg,$junky->version,$junky->channel,true);
	    }
	  }
	  
	  $base=sysvar::get('apps')."/$pkg->pkg/$pkg->channel/$pkg->version";

	  new api\bash\rm($base,array('r'));
	  
	  log::register("UNINSTALL_APP: App folder successfully deleted in $pkg->pkg/$pkg->channel/$pkg->version");
	  
	  aptitude::delete((int)$pkg->id);
	  
	  log::register("UNINSTALL_APP: App successfully uninstalled :)");
	}
}
